package com.snake.springboot.authority.service.impl;

import com.snake.springboot.authority.api.model.VerifyImageModel;
import com.snake.springboot.authority.api.service.VerifyImageService;
import com.snake.springboot.authority.service.utils.VerifyImageUtils;
import org.snake.common.code.SerialNumberGeneratorFactory;
import org.snake.common.exception.ParameterException;
import org.snake.redis.commons.RedisPlusUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

/**
 * 类 {@code VerifyImageServiceImpl}  <br> .
 * <p>验证码图片验证业务类
 * <p>创建时间：2024/11/29
 * @author yxt
 */
@Service
public class VerifyImageServiceImpl implements VerifyImageService {
    private RedisPlusUtils redisPlusUtils;
    private String Sub_Url = "static/verification/sub.png";
    private String Background_Url = "static/verification/img%s.jpg";
    @Autowired
    public VerifyImageServiceImpl(RedisPlusUtils redisPlusUtils) {
        this.redisPlusUtils = redisPlusUtils;
    }

    @Override
    public VerifyImageModel createVerifyImage() throws Exception {

        InputStream subInputStream = getInputStream(Sub_Url);
        Random random = new Random();
        InputStream backgroundInputStream = getInputStream(String.format(Background_Url, random.nextInt(4)+1));
        VerifyImageModel result = VerifyImageUtils.pictureTemplatesCut(subInputStream, backgroundInputStream);
        result.setUniqueId(SerialNumberGeneratorFactory.buildId4Bean());
        String redisKey = "authority:verifyImageCache:"+result.getUniqueId();
        redisPlusUtils.setOpsVal(redisKey,result.getXWidth(),90);
        result.setXWidth(null);
        return result;
    }

    @Override
    public boolean checkVerifyImage(VerifyImageModel model) {
        String redisKey = "authority:verifyImageCache:"+model.getUniqueId();
        Double xPos = redisPlusUtils.getOpsVal(redisKey, Double.class);
        Double xValue = model.getXWidth();
        if(xPos==null){
            throw new ParameterException("验证码过时或不存在，请重新获取");
        }
        else if(xPos-xValue>5||xPos-xValue<-5){
            throw new ParameterException("验证码不正确");
        }else{
            redisPlusUtils.delKey(redisKey);
            return true;
        }
    }


    private InputStream getInputStream(String str_url) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource(str_url);
        InputStream inputStream = classPathResource.getInputStream();
        return inputStream;
    }
}
